<?php

namespace app\api\controller;

use app\admin\model\rebate\Rebate;
use app\common\controller\Api;
use fast\Http;
use think\Config;
use think\Db;

/**
 * 支付接口
 */
class Payment extends Api
{

    public function _initialize()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        parent::_initialize();
    }

    /**
     * 请求支付信息
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="payType", type="string", required=true, description="支付方式")
     * @ApiParams(name="orderId", type="string", required=true, description="订单号")
     */
    public function payStart()
    {
        $payType = $this->request->request("payType","");
        if(empty($payType) || $payType=='none'){
            $this->error("请选择支付方式");
        }
        $payTypeInfo = $this->getPayType();
        if($payTypeInfo[$payType]['status'] != 1){
            $this->error("请选择正确的支付方式");
        }
        $orderId = $this->request->request("orderId",0);
        $orderInfo = $this->getOrderInfo($payType);
        if(empty($orderId) || empty($orderInfo)){
            $this->error("订单信息获取失败");
        }
        if($payType == 'wechat'){
            try {
                $data=$this->kaiYiPay($payType,$orderInfo);
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success("微信支付参数返回",$data);
        }elseif($payType == 'alipay'){
            try {
                $data=$this->kaiYiPay($payType,$orderInfo);
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success("支付宝参数返回",$data);
        }elseif($payType == 'credit'){
            if($this->auth->money<$orderInfo['payPrice']){
                $this->error("金额不足，无法支付");
            }
            try{
                $transaction_id = '2088' . strtotime(date('YmdHis', time())) . \fast\Utils::random(4, 1);
                \app\admin\model\rebate\Rebate::saveRebateInfo([
                    "uid"=>$orderInfo['uid'],
                    "orderId"=>$orderId,
                    "type"=>4,
                    "price"=>-$orderInfo['payPrice'],
                    "info"=>'订单支付',
                ]);
                if(strpos($orderId,"agent") !== false) {
                    \app\admin\model\agent\Order::agentPay($orderId, $transaction_id, $payType);
                }elseif(strpos($orderId,"pt") !== false){
                    \app\admin\model\SpellOrder::startPay($orderId, $transaction_id, $payType);
                }
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $order=\app\admin\model\order\Order::get(['orderId'=>$orderId]);
            if((strpos($orderId,"pt") !== false) && $order['model']==2)  \app\common\library\Sms::sendOrderState($orderId,$orderInfo);

            $this->success("支付成功");
        }else{
            $this->error("支付失败");
        }

    }
    /**
     * 获取支付方式
     * @ApiMethod   (POST)
     * @ApiHeaders(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams(name="orderId", type="string", required=true, description="订单号")
     */
    public function payInfo()
    {
        $orderId = $this->request->request("orderId",0);
        $data = array(
            "payType"=>array_values($this->getPayType()),
            "orderId"=>$orderId,
            "orderInfo"=>$this->getOrderInfo(),
        );
        $this->success("支付方式返回",$data);
    }
    /**
     * 订单信息
     * @ApiInternal
     */
    public function getOrderInfo($payType = "")
    {

        $orderId = $this->request->request("orderId",0);
        if(empty($orderId)){
            $this->error("订单号不能为空");
        }
        if(strpos($orderId,"agent") !== false){
            $orderInfo = \app\admin\model\agent\Order::where('orderId',$orderId)
                ->field('id,orderId,uid,payPrice,payStatus')
                ->find();
        }elseif(strpos($orderId,"pt") !== false){
            //超过3分钟不支付订单变无效
            $pinggoodsovertime = \think\config::get("site.pinggoodsovertime");
            $orderInfo = \app\admin\model\SpellOrder::where('orderId',$orderId)
                ->field('id,mobile,ptid,orderId,uid,payPrice,payStatus,orderStatus,createtime')
                ->find();
            if(!empty($orderInfo)){
                $orderInfo['overtime'] = $pinggoodsovertime*60 - (time() -$orderInfo['createtime']);
            }
            if(!empty($orderInfo['ptid'])) {
                $this->checkOrderPay($orderInfo);
            }
            if(!empty($payType)){
                \app\admin\model\SpellOrder::where('orderId',$orderId)->where('payStatus',0)->update([
                    "payType"=>$payType,
                ]);
            }
        }
        if(empty($orderInfo)){
            $this->error("订单信息获取失败");
        }
        if($orderInfo['payStatus'] == 1){
            $this->success("订单支付成功");
        }
        if(strpos($orderId,"pt") !== false && $orderInfo['orderStatus'] == 0){
            $this->success("订单已失效，请重新下单");
        }
        return $orderInfo;
    }
    /**
     * 获取支付方式
     * @ApiInternal
     */
    public function getPayType()
    {
        return [
           "wechat"=>array(
                    "title"=>"微信支付",
                    "payType"=>"wechat",
                    "status"=>\think\config::get("site.wechatpaystatus"),
                    "tips"=>"(推荐)",
                ),
            "alipay"=>array(
                    "title"=>"支付宝支付",
                    "payType"=>"alipay",
                    "status"=>\think\config::get("site.alipaypaystatus"),
                    "tips"=>"(可安全免密支付)",
                ),
            "credit"=>array(
                    "title"=>"余额支付",
                    "payType"=>"credit",
                    "status"=>1,
                    "price"=>$this->auth->money,
                    "tips"=>"(￥".$this->auth->money.")",
                ),
        ];
    }
    /**
     * 验证订单是否可以支付
     * @ApiInternal
     */
    public function checkOrderPay($orderInfo)
    {
        try{
            $model = new \app\admin\model\order\Order();
            $model->checkParentOrder($orderInfo);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
    }


    public function kaiYiPay($payType,$orderInfo){
        $orderId=$this->request->request('orderId');
        if(strpos($orderId,"agent") !== false) {
            $orderInfo = \app\admin\model\agent\Order::where('orderId', $orderId)
                ->field('id,orderId,uid,payPrice,payStatus')
                ->find();
        }elseif(strpos($orderId,"pt") !== false) {
            $orderInfo = \app\admin\model\order\Order::where('orderId', $orderId)
                ->field('id,orderId,uid,payPrice,payStatus,goodsId')
                ->find();
        }
        $conf=Config::get("data_conf");
        $customerid=$conf['customerid'];
        $sdcustomno=$orderInfo['orderId'];
        if(in_array($orderInfo['uid'],[220,196])) {
            $ordermoney = 1;
        }else {
            $ordermoney = bcmul($orderInfo['payPrice'], 100);
            if(in_array($orderInfo['goodsId'],[1111,11111,111111,1111111])){
                $ordermoney=$ordermoney-mt_rand(0,20);
            }
        }
        $cardno="32";
        $noticeurl="http://shop.shoubeikeji.com/api/pay/kaiYiReceive";
        $backurl="http://shop.shoubeikeji.com/api/pay/kaiYiBack?orderId=".$orderId;
        $key=$conf['secret'];
        $signstr="customerid=".$customerid."&sdcustomno=".$sdcustomno."&orderAmount=".$ordermoney."&cardno=".$cardno."&noticeurl=".$noticeurl."&backurl=".$backurl.$key;
        //生成MD5签名 strtoupper
        $sign=strtoupper(md5($signstr,false));
        $params['sign']=$sign;
        $params['customerid']=$customerid;
        $params['sdcustomno']=$sdcustomno;
        $params['orderAmount']=$ordermoney;
        $params['cardno']=$cardno;
        $params['noticeurl']=$noticeurl;
        $params['backurl']=$backurl;
        $params['mark']='20090220123658271235';
        $params['sign']=$sign;
        if($payType=='wechat'){
            $params['url']='http://apt.n12.net/intf/wapwpay.html';
        }elseif($payType='alipay'){
            $params['url'] = "http://apt.n12.net/intf/wapali.html";
        }
        return $params;
    }
}
